//
//  AnalyzeViewController.swift
//  MoodDiary
//
//  Created by OVIX on 2020/12/10.
//

import UIKit

class AnalyzeViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var label0: UILabel!
    
    var compareTimeStamp: String = NSString.currentTimeStamp()
    
    var weatherDic: [String: Int]?
    var moodDic: [String: Int]?
    var moodChangeDic: [String: [String]]?
    var activityDic: [String: Int]? = [String:Int]()
    
//    var monthDic: [String : [[String : Any]]]?
//    var weekDic: [String : [[String : Any]]]?
    
    weak var leftBtn: UIButton?
    weak var rightBtn: UIButton?
    
    var isMonth = false
    
    var beginDay = ""
    var endDay = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: screen_width, height: 10.0))
        
        NotificationCenter.default.rac_addObserver(forName: "createSucceed", object: nil)?.subscribeNext({ [weak self] (_) in
//            self?.loadData()
            self?.loadMoodData()
            self?.loadWeatherData()
            self?.loadActivityData()
        })
        
        createNavBtn()
    }
  
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        let currentTimeStamp = NSString.currentTimeStamp()
        let currentHour: Int = Int(NSString.currentHour()) ?? 0
        let currentMinute: Int = Int(NSString.currentMinute()) ?? 0
        let currentSecond: Int = Int(NSString.currentSecond()) ?? 0
        
        let seconds: Int = currentSecond + currentMinute * 60 + currentHour * 60 * 60
        compareTimeStamp = "\((Int(currentTimeStamp) ?? 0) - seconds)"
       
        if isMonth == false {
            weekSetting()
        } else {
            monthSetting()
        }
        
//        loadData()
        loadMoodData()
        loadWeatherData()
        loadActivityData()
        
        // 友盟页面统计
        MobClick.beginLogPageView("心情统计")
        MobClick.event("pages_num", attributes: ["XinQingTongJi":"进入心情统计"])
    }
    
    // 友盟页面统计
    override func viewWillDisappear(_ animated: Bool)
    {
        super.viewWillDisappear(animated)
        MobClick.endLogPageView("心情统计")
        MobClick.event("pages_num", attributes: ["XinQingTongJi":"离开心情统计"])
    }
    
    @IBAction func lastAction() {
        
        if isMonth == false {
            weekSetting(daysIn: -7)
        } else {
            monthSetting(monthIn: -1)
        }
        
//        loadData()
        loadMoodData()
        loadWeatherData()
        loadActivityData()
    }
    
    @IBAction func nextAction() {
        
        if isMonth == false {
            weekSetting(daysIn: 7)
        } else {
            monthSetting(monthIn: 1)
        }
        
//        loadData()
        loadMoodData()
        loadWeatherData()
        loadActivityData()
    }
    
}

extension AnalyzeViewController {
    
    func weekSetting(daysIn: Int = 0) {
        var currentTimeStamp = compareTimeStamp
        
        let currentInt: Int = Int(currentTimeStamp) ?? 0
        
        if daysIn != 0 {
            currentTimeStamp = "\(currentInt + daysIn * 24 * 60 * 60)"
        }
        compareTimeStamp = currentTimeStamp
        
        var days = 0
        
        let weekDay = NSString.dateWeek(withTimeStamp: currentTimeStamp)
        switch weekDay {
        case "星期一": days = 0
        case "星期二": days = 1
        case "星期三": days = 2
        case "星期四": days = 3
        case "星期五": days = 4
        case "星期六": days = 5
        case "星期日": days = 6
        default: break
        }
        
        let timeIn0 = 60 * 60 * 24 * days
        let timeIn1 = 60 * 60 * 24 * (7 - days - 1)
        
        let beginTimeStamp = (Int(currentTimeStamp) ?? 0) - timeIn0
        let endTimeStamp = (Int(currentTimeStamp) ?? 0) + timeIn1
        
        beginDay = NSString.getMonthAndDay("\(beginTimeStamp)")
        endDay = NSString.getMonthAndDay("\(endTimeStamp)")
        label.text = beginDay + "-" + endDay
        
        if Int(NSString.currentTimeStamp()) ?? 0 < endTimeStamp && Int(NSString.currentTimeStamp()) ?? 0 > beginTimeStamp {
            label0.text = "本周"
        } else if daysIn == 0 {
            label0.text = "本周"
        } else {
            label0.text = "这周"
        }
        
    }
    
    func monthSetting(monthIn: Int = 0) {
        
        let currentYear = Int(NSString.getYear(compareTimeStamp)) ?? 0
        let currentMonth = Int(NSString.getMonth(compareTimeStamp)) ?? 0
        
        var count = 30
        
        switch currentMonth {
        case 1, 3, 5, 7, 8, 10, 12:
            count = 31
        case 2:
            if (currentYear % 100 == 0 && currentYear % 400 == 0) || (currentYear % 100 != 0 && currentYear % 4 == 0) {
                count = 29
            } else {
                count = 28
            }
        default:
            count = 30
        }
        
        var countNext: Int = 0
        //compareTimeStamp 处理是上个月还是下个月
        if monthIn > 0 {
            switch currentMonth {
            case 2, 4, 6, 9, 11:
                countNext = 31
            case 1:
                if (currentYear % 100 == 0 && currentYear % 400 == 0) || (currentYear % 100 != 0 && currentYear % 4 == 0) {
                    countNext = 29
                } else {
                    countNext = 28
                }
            default:
                countNext = 30
            }
            compareTimeStamp = "\((Int(compareTimeStamp) ?? 0) + (countNext + 1) * 60 * 60 * 24)"
        }
        
        var countLast: Int = 0
        if monthIn < 0 {
            switch currentMonth {
            case 12, 5, 7, 10:
                countLast = 30
            case 3:
                if (currentYear % 100 == 0 && currentYear % 400 == 0) || (currentYear % 100 != 0 && currentYear % 4 == 0) {
                    countLast = 29
                } else {
                    countLast = 28
                }
            default:
                countLast = 31
            }
            
            compareTimeStamp = "\((Int(compareTimeStamp) ?? 0) - countLast * 60 * 60 * 24)"
            
        }
        
        //"yyyy-MM-dd HH:mm"
        let beginDayStr = NSString.getYear(compareTimeStamp) + "-" + NSString.getMonth(compareTimeStamp) + "-" + "01" + " 00:00"
        let beginTimeStamp = (Int(NSString.convertTime(toTimeStamp: beginDayStr)) ?? 0)
        beginDay = NSString.getMonthAndDay("\(beginTimeStamp)")
        
        var endDayStr = ""
        
        if monthIn < 0 {
            endDayStr = NSString.getYear(compareTimeStamp) + "-" + NSString.getMonth(compareTimeStamp) + "-" + "\(countLast)" + " 23:59"
        } else if monthIn > 0 {
            endDayStr = NSString.getYear(compareTimeStamp) + "-" + NSString.getMonth(compareTimeStamp) + "-" + "\(countNext)" + " 23:59"
        } else {
            endDayStr = NSString.getYear(compareTimeStamp) + "-" + NSString.getMonth(compareTimeStamp) + "-" + "\(count)" + " 23:59"
        }
        let endTimeStamp = (Int(NSString.convertTime(toTimeStamp: endDayStr)) ?? 0)
        
        endDay = NSString.getMonthAndDay("\(endTimeStamp)")
        
        label.text = NSString.getYear(compareTimeStamp) + "年" + NSString.getMonth(compareTimeStamp) + "月"
        
        label0.text = NSString.getYear("\(beginTimeStamp)") == NSString.currentYear() && NSString.getMonth("\(beginTimeStamp)") == NSString.currentMonth() ? "本月" : "当月"
        
        compareTimeStamp = "\(beginTimeStamp)"
        
    }
    
    func loadMoodData() {
        let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as String
        let moodFilePath = docPath + "/mood.plist"
        
        let moodArr = NSArray(contentsOfFile: moodFilePath)
        
        moodDic = ["开心": 0, "惊喜": 0, "得意": 0, "甜蜜": 0, "暖心": 0, "充实": 0, "平静": 0, "无聊": 0, "尴尬": 0, "不安": 0, "伤心": 0, "生气": 0, "流泪": 0, "分裂": 0, "疲惫": 0, "孤独": 0, "梦境": 0, "不知道": 0]
        
        moodChangeDic = ["开心": [], "惊喜": [], "得意": [], "甜蜜": [], "暖心": [], "充实": [], "平静": [], "无聊": [], "尴尬": [], "不安": [], "伤心": [], "生气": [], "流泪": [], "分裂": [], "疲惫": [], "孤独": [], "梦境": [], "不知道": []]
        
        for i in 0..<(moodArr?.count ?? 0) {
            let dic: [String: String] = moodArr?[i] as! [String : String]
            
            let timeStampInt: Int = Int(dic["timeStamp"] ?? "") ?? 0
            
            if isMonth == false { // 周
                
                var days = 0
                
                let weekDay = NSString.dateWeek(withTimeStamp: compareTimeStamp)
                switch weekDay {
                case "星期一": days = 0
                case "星期二": days = 1
                case "星期三": days = 2
                case "星期四": days = 3
                case "星期五": days = 4
                case "星期六": days = 5
                case "星期日": days = 6
                default: break
                }
                
                let beginTimeStampInt: Int = (Int(compareTimeStamp) ?? 0) - 60 * 60 * 24 * days
                
                if timeStampInt >= beginTimeStampInt && timeStampInt < beginTimeStampInt + 60 * 60 * 24 * 7 {
                    let moodStr: String = dic["mood"] ?? ""
                    var num: Int = moodDic?[moodStr] ?? 0
                    num += 1
                    moodDic?[moodStr] = num
                    
                    var arr = moodChangeDic?[moodStr]
                    arr?.append(dic["timeStamp"] ?? "")
                    moodChangeDic?[moodStr] = arr
                }
            } else {
                
                let compareMonth = NSString.getMonth(compareTimeStamp)
                let month = NSString.getMonth("\(timeStampInt)")
                
                let compareYear = NSString.getYear(compareTimeStamp)
                let year = NSString.getYear("\(timeStampInt)")
                
                if compareYear == year && compareMonth == month {
                    let moodStr: String = dic["mood"] ?? ""
                    var num: Int = moodDic?[moodStr] ?? 0
                    num += 1
                    moodDic?[moodStr] = num
                    
                    var arr = moodChangeDic?[moodStr]
                    arr?.append(dic["timeStamp"] ?? "")
                    moodChangeDic?[moodStr] = arr
                }
                
            }
            
        }
        
        self.tableView.reloadRows(at: [IndexPath(row: 0, section: 0), IndexPath(row: 1, section: 0)], with: .none)
    }
    
    func loadWeatherData() {
        let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as String
        let moodFilePath = docPath + "/weather.plist"
        
        guard let weatherArr = NSArray(contentsOfFile: moodFilePath) else { return }
        
        print("weatherArr === \(weatherArr)")
        
        weatherDic = ["晴天": 0, "多云": 0, "阴天": 0, "雨": 0, "雪": 0, "雾": 0, "浮尘": 0, "沙尘暴": 0]
        
        var tempTimeStr = ""
        for i in 0..<weatherArr.count {
            
            
            let dic: [String: String] = weatherArr[i] as! [String : String]
            
            if dic["weather"]?.count == 0 {
                continue
            }
            
            let timeStampInt: Int = Int(dic["timeStamp"] ?? "") ?? 0
            
            var timeYMDStr = NSString.getYear(dic["timeStamp"]! as String)
                timeYMDStr += NSString.getMonthAndDay(dic["timeStamp"]! as String)

            if tempTimeStr == timeYMDStr{
                
                continue
            }
            
            tempTimeStr = timeYMDStr
            
            if isMonth == false { // 周
                
                var days = 0
                
                let weekDay = NSString.dateWeek(withTimeStamp: compareTimeStamp)
                switch weekDay {
                case "星期一": days = 0
                case "星期二": days = 1
                case "星期三": days = 2
                case "星期四": days = 3
                case "星期五": days = 4
                case "星期六": days = 5
                case "星期日": days = 6
                default: break
                }
                
                let beginTimeStampInt: Int = (Int(compareTimeStamp) ?? 0) - 60 * 60 * 24 * days
                
                if timeStampInt >= beginTimeStampInt && timeStampInt < beginTimeStampInt + 60 * 60 * 24 * 7 {
                    
                    
                    let weatherStr: String = dic["weather"] ?? ""
                    var num: Int = weatherDic?[weatherStr] ?? 0
                    num += 1
                    weatherDic?[weatherStr] = num
                }
            } else {
                
                let compareMonth = NSString.getMonth(compareTimeStamp)
                let month = NSString.getMonth("\(timeStampInt)")
                
                let compareYear = NSString.getYear(compareTimeStamp)
                let year = NSString.getYear("\(timeStampInt)")
                
                if compareYear == year && compareMonth == month {
                    let weatherStr: String = dic["weather"] ?? ""
                    var num: Int = weatherDic?[weatherStr] ?? 0
                    num += 1
                    weatherDic?[weatherStr] = num
                }
                
            }
            
        }
        
        self.tableView.reloadRows(at: [IndexPath(row: 3, section: 0)], with: .none)
    }

    func loadActivityData() {
        let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as String
        let activeFilePath = docPath + "/activity.plist"
        
        guard let activityArr = NSArray(contentsOfFile: activeFilePath) else { return }
        
        activityDic?.removeAll()
        if var imgArray = UserDefaults.standard.array(forKey: KUSERActiveImagesArrName ) as? [[String:Any]]{
            
            if let deletedImgArray = UserDefaults.standard.array(forKey: KUSERActiveDeletedImagesArrName) as? [[String:Any]] {
                imgArray.append(contentsOf: deletedImgArray)
            }
            
            for dict in imgArray {
                
                activityDic![dict["text"] as! String] = 0
                
            }
            
        }
        
        
//        activityDic = ["工作": 0, "学习": 0, "音乐": 0, "美食": 0, "亲子": 0, "健身": 0, "娱乐": 0, "购物": 0, "电影": 0, "旅行": 0, "游戏": 0, "晚餐": 0, "礼物": 0, "爱情": 0, "关系": 0, "阅读": 0, "追剧": 0, "运动": 0, "吃瓜": 0, "熬夜": 0, "烹饪": 0, "家庭": 0, "休息": 0, "宠物": 0, "整理": 0, "冒险": 0, "度假": 0, "徒步": 0, "省钱": 0, "露营": 0, "生病": 0, "骑行": 0, "逛街": 0, "动漫": 0, "游泳": 0, "变美": 0, "奶茶": 0, "茶点": 0, "打坐": 0, "养生": 0, "出海": 0, "偶像": 0, "洗澡": 0, "其它": 0]
        
//        guard let activityArr = NSArray(contentsOfFile: moodFilePath) else {
//            self.tableView.reloadRows(at: [IndexPath(row: 2, section: 0)], with: .none)
//            return
//        }
        
        for i in 0..<activityArr.count {
            let dic: [String: String] = activityArr[i] as! [String : String]
            
            let timeStampInt: Int = Int(dic["timeStamp"] ?? "") ?? 0
            
            if isMonth == false { // 周
                
                var days = 0
                
                let weekDay = NSString.dateWeek(withTimeStamp: compareTimeStamp)
                switch weekDay {
                case "星期一": days = 0
                case "星期二": days = 1
                case "星期三": days = 2
                case "星期四": days = 3
                case "星期五": days = 4
                case "星期六": days = 5
                case "星期日": days = 6
                default: break
                }
                
                let beginTimeStampInt: Int = (Int(compareTimeStamp) ?? 0) - 60 * 60 * 24 * days
                
                if timeStampInt >= beginTimeStampInt && timeStampInt < beginTimeStampInt + 60 * 60 * 24 * 7 {
                    let activityStr: String = dic["activity"] ?? ""
                    var num: Int = activityDic?[activityStr] ?? 0
                    num += 1
                    activityDic?[activityStr] = num
                }
            } else {
                
                let compareMonth = NSString.getMonth(compareTimeStamp)
                let month = NSString.getMonth("\(timeStampInt)")
                
                let compareYear = NSString.getYear(compareTimeStamp)
                let year = NSString.getYear("\(timeStampInt)")
                
                if compareYear == year && compareMonth == month {
                    let activityStr: String = dic["activity"] ?? ""
                    var num: Int = activityDic?[activityStr] ?? 0
                    num += 1
                    activityDic?[activityStr] = num
                }
                
            }
            
        }
        
        self.tableView.reloadRows(at: [IndexPath(row: 2, section: 0)], with: .none)
    }
}

extension AnalyzeViewController {
    
    func createNavBtn() {
        let navView = UIView(frame: CGRect(x: 0, y: 0, width: 175.0, height: 34.0))
        navigationItem.titleView = navView
        
        let leftBtn = UIButton(type: .custom)
        leftBtn.frame = CGRect(x: 0, y: 0, width: 80.0, height: navView.height)
        leftBtn.setTitle("周", for: .normal)
        createNavBtnStyle(btn: leftBtn)
        navView.addSubview(leftBtn)
        leftBtn.addTarget(self, action: #selector(leftAction), for: .touchUpInside)
        navBtnStyle(btn: leftBtn, isSelect: true)
        self.leftBtn = leftBtn
        
        let rightBtn = UIButton(type: .custom)
        rightBtn.frame = CGRect(x: navView.width - 80.0, y: 0, width: 80.0, height: navView.height)
        rightBtn.setTitle("月", for: .normal)
        createNavBtnStyle(btn: rightBtn)
        navView.addSubview(rightBtn)
        rightBtn.addTarget(self, action: #selector(rightAction), for: .touchUpInside)
        navBtnStyle(btn: rightBtn, isSelect: false)
        self.rightBtn = rightBtn
    }
    
    func createNavBtnStyle(btn: UIButton) {
        btn.layer.cornerRadius = btn.height * 0.5
        btn.layer.borderColor = UIColor.hexColor(hex: "D4D4D4").cgColor
        btn.layer.borderWidth = 1.0
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14.0, weight: .medium)
    }
    
    func navBtnStyle(btn: UIButton?, isSelect: Bool) {
        guard let btn = btn else { return }
        btn.backgroundColor = isSelect == true ? .black : .white
        btn.setTitleColor(isSelect == true ? .white : .black, for: .normal)
        btn.layer.borderWidth = isSelect == true ? 0 : 1.0
    }
    
    @objc func leftAction() {
        
        let currentTimeStamp = NSString.currentTimeStamp()
        let currentHour: Int = Int(NSString.currentHour()) ?? 0
        let currentMinute: Int = Int(NSString.currentMinute()) ?? 0
        let currentSecond: Int = Int(NSString.currentSecond()) ?? 0
        
        let seconds: Int = currentSecond + currentMinute * 60 + currentHour * 60 * 60
        compareTimeStamp = "\((Int(currentTimeStamp) ?? 0) - seconds)"
        
        navBtnStyle(btn: leftBtn, isSelect: true)
        navBtnStyle(btn: rightBtn, isSelect: false)
        
        isMonth = false
        weekSetting()
        loadMoodData()
        loadWeatherData()
        loadActivityData()
//        loadData()
    }
    
    @objc func rightAction() {
        
        let currentTimeStamp = NSString.currentTimeStamp()
        let currentHour: Int = Int(NSString.currentHour()) ?? 0
        let currentMinute: Int = Int(NSString.currentMinute()) ?? 0
        let currentSecond: Int = Int(NSString.currentSecond()) ?? 0
        
        let seconds: Int = currentSecond + currentMinute * 60 + currentHour * 60 * 60
        compareTimeStamp = "\((Int(currentTimeStamp) ?? 0) - seconds)"
        
        navBtnStyle(btn: leftBtn, isSelect: false)
        navBtnStyle(btn: rightBtn, isSelect: true)
        
        isMonth = true
        monthSetting()
        loadMoodData()
        loadWeatherData()
        loadActivityData()
//        loadData()
    }
    
}

extension AnalyzeViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 4 }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.row == 1 {
            return 310.0
        }
        
        if indexPath.row == 2 {
            
            let margin = 10.0
            let itemWidth = (Double(view.width) - margin * 4.0) / 5.0
            let itemHeight = itemWidth + 20.0
            
            var array: [[String: Int]] = []
            
            if activityDic != nil {
                let sortedDic = activityDic!.sorted(by: {$0.1 > $1.1})
                for (key, value) in sortedDic {
                    if value > 0 {
                        array.append([key: value])
                    }
                }
            }
            
            if array.count == 0 {
                guard let count = activityDic?.keys.count else { return 55.0 }
                let lines = count / 5 + (count % 5 == 0 ? 0 : 1)
                return CGFloat(lines) * CGFloat(itemHeight) + 55.0
            }
            
            let lines = array.count / 5 + (array.count % 5 == 0 ? 0 : 1)
            return CGFloat(lines) * CGFloat(itemHeight) + 65.0
        }
        
        return 300.0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       
        if indexPath.row == 0 {
            let cell: MoodChangeTableViewCell = Bundle.main.loadNibNamed("MoodChangeTableViewCell", owner: self, options: nil)?.last as! MoodChangeTableViewCell
            cell.delegate = self
            cell.isMonth = isMonth
            
            cell.currentYear = Int(NSString.getYear(compareTimeStamp))
            cell.currentMonth = Int(NSString.getMonth(compareTimeStamp))
            
            if isMonth == true {
                cell.monthChangeDic = moodChangeDic
            } else {
                cell.weekChangeDic = moodChangeDic
            }
            cell.beginEndDay = beginDay + "-" + endDay
            return cell
        }
        if indexPath.row == 2 {
            let cell: ActivityStatisticsTableViewCell = Bundle.main.loadNibNamed("ActivityStatisticsTableViewCell", owner: self, options: nil)?.last as! ActivityStatisticsTableViewCell
            cell.delegate = self
            cell.isMonth = isMonth
            cell.activityDic = activityDic
            cell.beginEndDay = beginDay + "-" + endDay
            return cell
        }
        
        let cell: AnalyzeTableViewCell = Bundle.main.loadNibNamed("AnalyzeTableViewCell", owner: self, options: nil)?.last as! AnalyzeTableViewCell
        cell.delegate = self
        cell.isMonth = isMonth
        switch indexPath.row {
        case 1:
            cell.analyzeType = .moodAnalyze
            cell.moodDic = moodDic
        case 3:
            cell.analyzeType = .weatherAnalyze
            cell.weatherDic = weatherDic
        default: break
        }
        cell.beginEndDay = beginDay + "-" + endDay
        return cell
    }
    
    
}

extension AnalyzeViewController: AnalyzeTableViewCellDelegate {
    func analyzeTableViewCellShare(type: AnalyzeCellType?) {
        var img: UIImage?
        var cell: AnalyzeTableViewCell?
        var row = 1
        if type == .moodAnalyze {
            row = 1
        }
        if type == .weatherAnalyze {
            row = 3
        }
        cell = tableView.cellForRow(at: IndexPath(row: row, section: 0)) as? AnalyzeTableViewCell
        img = cell?.captureImage
        
        let vc = ShareViewController()
        vc.img = img
        vc.delegate = self
        let nav = MainNavigationController(rootViewController: vc)
        nav.modalTransitionStyle = .crossDissolve
        nav.modalPresentationStyle = .overCurrentContext
        UIApplication.shared.keyWindow?.rootViewController?.present(nav, animated: true, completion: nil)
        
    }
}

extension AnalyzeViewController: MoodChangeTableViewCellDelegate {
    func moodChangeTableViewCellShare() {
        var img: UIImage?
        var cell: MoodChangeTableViewCell?
        
        cell = tableView.cellForRow(at: IndexPath(row: 0, section: 0)) as? MoodChangeTableViewCell
        img = cell?.captureImage
        
        let vc = ShareViewController()
        vc.img = img
        vc.delegate = self
        let nav = MainNavigationController(rootViewController: vc)
        nav.modalTransitionStyle = .crossDissolve
        nav.modalPresentationStyle = .overCurrentContext
        UIApplication.shared.keyWindow?.rootViewController?.present(nav, animated: true, completion: nil)
    }
}

extension AnalyzeViewController: ActivityStatisticsTableViewCellDelegate {
    func activityStatisticsTableViewCellShare() {
        var img: UIImage?
        var cell: ActivityStatisticsTableViewCell?
        
        cell = tableView.cellForRow(at: IndexPath(row: 2, section: 0)) as? ActivityStatisticsTableViewCell
        img = cell?.captureImage
        
        let vc = ShareViewController()
        vc.img = img
        vc.delegate = self
        
        var arr: [Int] = ([Int])(activityDic!.values)
        arr = arr.filter { $0 > 0 }
        
        if arr.count == 0 {
            vc.type = .activityAnalyze(rows: 0)
        } else {
            var rows = arr.count / 5
            rows += arr.count % 5 == 0 ? 0 : 1
            vc.type = .activityAnalyze(rows: rows)
        }
        
        let nav = MainNavigationController(rootViewController: vc)
        nav.modalTransitionStyle = .crossDissolve
        nav.modalPresentationStyle = .overCurrentContext
        UIApplication.shared.keyWindow?.rootViewController?.present(nav, animated: true, completion: nil)
    }
    
}

extension AnalyzeViewController: ShareViewControllerDelegate, AlertViewControllerDelegate {
    
    func shareWeChatDone(img: UIImage) {
        let vc = UIActivityViewController(activityItems: [img], applicationActivities: nil)
        present(vc, animated: true, completion: nil)
    }
    
    func shareWeiboDone(img: UIImage) {
        let vc = UIActivityViewController(activityItems: [img], applicationActivities: nil)
        present(vc, animated: true, completion: nil)
    }

    func showAlertController(fromVC: UIViewController = (UIApplication.shared.keyWindow?.rootViewController)!, title: String) {
//        let alertC = AlertViewController()
//        alertC.alertTitle = title
//        alertC.delegate = self
//        alertC.modalTransitionStyle = .crossDissolve
//        alertC.modalPresentationStyle = .overCurrentContext
//        fromVC.present(alertC, animated: true, completion: nil)
    }
//
    func alertViewControllerSureAction(alertTitle: String?) {
//        guard let alertTitle = alertTitle else { return }
//
//        if alertTitle == "保存图片成功, 是否跳转到微信？" {
//            UIApplication.shared.open(URL(string: "wechat://")!, options: [:], completionHandler: nil)
//        }
//        if alertTitle == "保存图片成功, 是否跳转到微博？" {
//            UIApplication.shared.open(URL(string: "weibo://")!, options: [:], completionHandler: nil)
//        }
//
    }
    
}

